//
//  Average.h
//  
//
//  Created by チョウ　コン on 2013/08/21.
//
//

#ifndef _Average_h
#define _Average_h
#include <kvs/StructuredVolumeObject>
#include <kvs/StructuredVolumeImporter>
#include "CreateString.h"

// month must be mm (e.g. 01, 02, 03...)
kvs::StructuredVolumeObject* Average( std::string data_type , std::string year, std::string month, size_t ndays )
{
    size_t nsteps = 8 * ndays;
    // load the first time step to get the resolution
    std::string base = "/media/HDCA-UT/Original/" + year + "/";
    std::string first_day = year + month + "01";
    std::string first_filename = base + first_day + "/" + "rm_rokka19_" + first_day + "__" + data_type + "_0000.kvsml";
    std::cout << "loading the first file: " << first_filename << std::endl;
    kvs::StructuredVolumeObject* volume_first = new kvs::StructuredVolumeImporter( first_filename );
    size_t nx = volume_first->resolution().x();
    size_t ny = volume_first->resolution().y();
    size_t nz = volume_first->resolution().z();
    
    // initialize the value array
    kvs::AnyValueArray values;
    float* pvalues = static_cast<float*>( values.allocate<float>( nx * ny * nz ) );
    for( size_t i = 0; i < nx * ny * nz; i++ )
    {
        pvalues[i] = 0.0;
    }
    
    // get average the value array
    for ( size_t j = 1; j <= ndays; j++ )
    {
        char buf[10];
        sprintf( buf, "%02d", (int)j );
        std::string day = year + month + std::string(buf);
        std::string directory = base + day + "/";
        for ( size_t i = 0; i < 8; i++ )
        {
            std::string filename = CreateString( directory + "rm_rokka19_" + day + "__" + data_type + "_0", i, "kvsml" );
            kvs::StructuredVolumeObject* volume_temp = new kvs::StructuredVolumeImporter( filename );
            std::cout << "finish loading: " << filename << std::endl;
            
            float* pvalues_temp = (float*)volume_temp->values().pointer();
            for( size_t m = 0; m < nx * ny * nz; m++ )
                pvalues[m] += pvalues_temp[m];
           
            delete volume_temp;
            //std::cout << "delete file: " << filename << std::endl;
        }
    }
    for( size_t i = 0; i < nx * ny * nz; i++ )
    {
        pvalues[i] = pvalues[i] / (float)nsteps;
    }
    
    kvs::Vector3ui resolution( nx, ny, nz );
    kvs::VolumeObjectBase::GridType grid_type = kvs::VolumeObjectBase::Uniform;
    kvs::StructuredVolumeObject* volume = new kvs::StructuredVolumeObject();
    volume->setGridType( grid_type);
    volume->setVeclen( 1 );
    volume->setResolution( resolution );
    volume->setValues( values );
    
    volume->updateMinMaxCoords();
    volume->updateMinMaxValues();
    return volume;
}

#endif
